package com.shanzhe.eshop.common.nio;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Author yinwei
 * @create 2021/12/25
 * @Version 1.0
 */
public class SocketClient {

    public static void main(String[] args) throws Exception{

        //此时会先找DNS服务查找域名对应的IP地址
        //接下来需要和那个IP地址上的9000的端口号的服务器进行tcp三次握手建立连接
        Socket socket = new Socket("localhost", 9000);

        InputStreamReader in = new InputStreamReader(socket.getInputStream());
        OutputStream out = socket.getOutputStream();
        char[] buf = new char[1024 * 1024];

        while (true){
            try {
                out.write("发送请求擦擦擦".getBytes());
                int len = in.read(buf);

                while (len!=-1){
                    String request = new String(buf,0,len);
                    System.out.println("客户端接受到了响应"+request);
                    //需要不停的读取socket流传输过来的数据 因为buf才1kb可能才读取流中1kb的数据后面可能还有很多数据所以需要不停的读取
                    len = in.read(buf);
                }
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
                in.close();
                out.close();
                socket.close();
            }
      }
    }
}
